import { defineStore } from 'pinia';
import { ref } from 'vue';

export const userTokenStore = defineStore('token', () => {
    // 从 localStorage 中获取 token，如果不存在则为空字符串
    const storedToken = localStorage.getItem('userToken') || '';
    const token = ref(storedToken);

    const setToken = (newToken) => {
        try {
            token.value = newToken;
            localStorage.setItem('userToken', newToken);
        } catch (error) {
            console.error('Failed to set token in localStorage:', error);
        }
    };

    const removeToken = () => {
        try {
            token.value = '';
            localStorage.removeItem('userToken');
        } catch (error) {
            console.error('Failed to remove token from localStorage:', error);
        }
    };

    return {
        token,
        setToken,
        removeToken,
    };
}/*,{
    persist:true              //使用组件持久化
}*/);